package com.lanca.filter;

import org.bouncycastle.util.encoders.UTF8;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;

@Component
public class UrlFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    /**
     * 不用这么麻烦把，springcloud提供有monitor接口可以自动转换。 config server添加
     * <dependency> <groupId>org.springframework.cloud</groupId>
     * <artifactId>spring-cloud-config-monitor</artifactId>
     * </dependency>
     * webhook地址将/actuator/bus-refresh改为 /monitor
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (!request.getRequestURI().endsWith("/bus-refresh")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 获取原始body
        String body = readAsChar(request);
        String replace = body.replace("\\r\\n\\t", "\r\n\t");

        String replace1 = replace.replace("\\u0000", "");
        String replace2 = replace1.replace("\u0000","");
        //String replace1 = replace.replace("&lt;br/&gt;", "\n");
        System.out.println("original body: " + body);
        System.out.println("original replace2: " + replace2);
        CustometRequestWrapper requestWrapper = new CustometRequestWrapper(request);
        requestWrapper.setCharacterEncoding("UTF-8");
        filterChain.doFilter(requestWrapper, response);
    }

    private String readAsChar(HttpServletRequest request) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder("");
        try {
            br = request.getReader();
            String str;
            while (((str = br.readLine())) != null) {
                sb.append(str);
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }


    private class CustometRequestWrapper extends HttpServletRequestWrapper {

        public CustometRequestWrapper(HttpServletRequest request) {
            super(request);
        }

        @Override
        public ServletInputStream getInputStream() throws IOException {
            byte[] bytes = new byte[0];
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            return new ServletInputStream() {
                @Override
                public boolean isFinished() {
                    return byteArrayInputStream.read() == -1;
                }

                @Override
                public boolean isReady() {
                    return false;
                }

                @Override
                public void setReadListener(ReadListener readListener) {

                }

                @Override
                public int read() throws IOException {
                    return 0;
                }
            };
        }
    }
}
